package org.jeecg.pms.controller;

import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections4.CollectionUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.pms.aspect.annotation.PmsLog;
import org.jeecg.pms.aspect.enums.ProjectLogType;
import org.jeecg.pms.entity.PmsTask;
import org.jeecg.pms.service.IPmsTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 项目管理模块-任务管理
 * @Author: MxpIO
 * @Date: 2021-2-16
 * @Version: V1.0
 */
@Api(tags="项目管理模块-任务管理")
@RestController
@RequestMapping("/pms/task")
@Slf4j
public class PmsTaskController extends JeecgController<PmsTask, IPmsTaskService>{
	@Autowired
	private IPmsTaskService pmsTaskService;
	
	/**
	 * 分页列表查询
	 *
	 * @param pmsTask
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
/*	@AutoLog(value = "项目管理模块-任务管理-分页列表查询")
	@ApiOperation(value="项目管理模块-任务管理-分页列表查询", notes="项目管理模块-任务管理-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(PmsTask pmsTask,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		String hasQuery = req.getParameter("hasQuery");
        if(hasQuery != null && "true".equals(hasQuery)){
            QueryWrapper<PmsTask> queryWrapper =  QueryGenerator.initQueryWrapper(pmsTask, req.getParameterMap());
            List<PmsTask> list = pmsTaskService.queryTreeListNoPage(queryWrapper);
            IPage<PmsTask> pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
            return Result.OK(pageList);
        }else{
            String parentTaskCode = pmsTask.getParentTaskCode();
            if (oConvertUtils.isEmpty(parentTaskCode)) {
            	parentTaskCode = "0";
            }
            pmsTask.setParentTaskCode(null);
            QueryWrapper<PmsTask> queryWrapper = QueryGenerator.initQueryWrapper(pmsTask, req.getParameterMap());
            // 使用 eq 防止模糊查询
            queryWrapper.eq("parent_task_code", parentTaskCode);
            Page<PmsTask> page = new Page<PmsTask>(pageNo, pageSize);
            IPage<PmsTask> pageList = pmsTaskService.page(page, queryWrapper);
            return Result.OK(pageList);
        }
	}*/
	
	/**
	 * 树表查询
	 *
	 * @param pmsTask
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "项目管理-任务树查询")
	@ApiOperation(value="项目管理-任务树查询", notes="项目管理-任务树查询")
	@GetMapping(value = "/treeList")
	public Result<?> queryTreeList(String projectCode,
								   HttpServletRequest req) {
		QueryWrapper<PmsTask> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("project_code", projectCode);
		queryWrapper.eq("parent_task_code", "0");
		// 获取1级节点
		List<PmsTask> list = pmsTaskService.list(queryWrapper);
		// 生成树
		List<PmsTask> resultList = pmsTaskService.queryTreeList(list);
		return Result.OK(resultList);
	}

	 /**
      * 获取子数据
      * @param pmsTask
      * @param req
      * @return
      */
	@AutoLog(value = "项目管理-任务列表查询")
	@ApiOperation(value="项目管理-任务列表查询", notes="项目管理-任务列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(PmsTask pmsTask,HttpServletRequest req) {
		QueryWrapper<PmsTask> queryWrapper = QueryGenerator.initQueryWrapper(pmsTask, req.getParameterMap());
		List<PmsTask> list = pmsTaskService.list(queryWrapper);
		for(PmsTask task : list){
			pmsTaskService.handleTransientVariable(task);
		}
		
		IPage<PmsTask> pageList = new Page<>(1, 10, list.size());
        pageList.setRecords(list);
		return Result.OK(pageList);
	}

    /**
      * 批量查询子节点
      * @param parentCodes 父code（多个采用半角逗号分割）
      * @return 返回 IPage
      * @param parentIds
      * @return
      */
	@AutoLog(value = "项目管理-批量获取子任务")
    @ApiOperation(value="项目管理-批量获取子任务", notes="项目管理-批量获取子任务")
    @GetMapping("/getChildListBatch")
    public Result<Object> getChildListBatch(@ApiParam(name = "parentCodes", value = "父任务code", required = true) @RequestParam("parentCodes") String parentCodes) {
        try {
            QueryWrapper<PmsTask> queryWrapper = new QueryWrapper<>();
            List<String> parentIdList = Arrays.asList(parentCodes.split(","));
            queryWrapper.in("parent_task_code", parentIdList);
            List<PmsTask> list = pmsTaskService.list(queryWrapper);
            IPage<PmsTask> pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
            return Result.OK(pageList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("批量查询子节点失败：" + e.getMessage());
        }
    }
	
	/**
	 *   添加
	 *
	 * @param pmsTask
	 * @return
	 */
	@AutoLog(value = "项目管理-任务添加")
	@ApiOperation(value="项目管理-任务添加", notes="项目管理-任务添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody PmsTask pmsTask) {
		try{
			pmsTaskService.addPmsTask(pmsTask);
		}catch (Exception e) {
			return Result.error("保存失败，请检查前置任务依赖关系！");
		}
		return Result.OK("添加成功！",pmsTask);
	}
	
	/**
	 *  编辑
	 *
	 * @param pmsTask
	 * @return
	 */
	@AutoLog(value = "项目管理-任务编辑")
	@ApiOperation(value="项目管理-任务编辑", notes="项目管理-任务编辑")
	@PutMapping(value = "/edit")
	@PmsLog(projectLogType = ProjectLogType.TASK)
	public Result<?> edit(@RequestBody PmsTask pmsTask) {
		try{
			pmsTaskService.updatePmsTask(pmsTask);
		}catch (Exception e) {
			return Result.error("保存失败，请检查前置任务依赖关系！");
		}
		
		return Result.OK("编辑成功!",pmsTask);
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "项目管理-通过id删除任务")
	@ApiOperation(value="项目管理-通过id删除任务", notes="项目管理-通过id删除任务")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="code",required=true) String code) {
		pmsTaskService.deletePmsTask(code);
		return Result.OK("删除成功!",null);
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "项目管理-批量删除任务")
	@ApiOperation(value="项目管理-批量删除任务", notes="项目管理-批量删除任务")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.pmsTaskService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！",null);
	}
	
	/**
	 * 通过code查询
	 *
	 * @param code
	 * @return
	 */
	@AutoLog(value = "项目管理-通过code查询任务")
	@ApiOperation(value="项目管理-通过code查询任务", notes="项目管理-通过code查询任务")
	@GetMapping(value = "/queryByCode")
	public Result<?> queryByCode(@RequestParam(name="code",required=true) String code) {
		List<PmsTask> pmsTasks = pmsTaskService.list(new QueryWrapper<PmsTask>().eq("task_code", code));
		if(CollectionUtils.isEmpty(pmsTasks)) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(pmsTasks.get(0));
	}
	
	/**
	 * 通过Code查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "项目管理-通过id查询任务")
	@ApiOperation(value="项目管理-通过id查询任务", notes="项目管理-通过id查询任务")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		PmsTask pmsTask = pmsTaskService.getById(id);
		if(pmsTask==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(pmsTask);
	}
	
	/**
	 * 计算任务时间
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "项目管理-计算任务时间")
	@ApiOperation(value="项目管理-计算任务时间", notes="项目管理-计算任务时间")
	@GetMapping(value = "/computeTaskTime")
	public Result<?> computeTaskTime(@RequestParam(name="projectCode",required=true) String projeckCode) {
		pmsTaskService.computeTaskTime(projeckCode);
		return Result.OK();
	}
	
	public Result<?> checkPreCode(@RequestParam(name="code",required=true) String code
			,@RequestParam(name="preCode",required=true) String preCode){
		return null;
	}
	
    /**
    * 导出excel
    *
    * @param request
    * @param pmsTask
    */
    @RequestMapping(value = "/exportXls")
    @ApiOperation(value="项目管理-任务导出excel", notes="项目管理-任务导出excel")
    public ModelAndView exportXls(HttpServletRequest request, PmsTask pmsTask) {
		return super.exportXls(request, pmsTask, PmsTask.class, "任务列表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    @ApiOperation(value="项目管理-任务导入excel", notes="项目管理-任务导入excel")
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		return super.importExcel(request, response, PmsTask.class);
    }
}
